﻿//**************** ajax_quenen BEGIN
var ajax_quenen = {
    quenen: [],
    push: function ($el, $index) {
        var matched = this.find($index);
        if (matched) return;

        this.quenen.push({
            orginal_text: $el.text(),
            $el: $el,
            is_requesting: false,
            index: $index
        });
    },
    find: function ($index) {
        var matched;

        $.each(this.quenen, function (index, data) {
            if ($index === data.index) matched = data;
        });
        return matched;
    },
    remove: function ($index) {
        var search_index = -1;

        $.each(this.quenen, function (index, data) {
            if ($index === data.index) search_index = index;
        });

        if (search_index > -1) this.quenen.splice(search_index, 1);
    },
    get_wait_for_request: function () {
        var len = this.quenen.length;

        for (var i = 0; i < len; i++) {
            if (this.quenen[i].is_requesting) continue;
            return this.quenen[i];
        }
    }
};
//**************** ajax_quenen END

/**
*   使用方法： 在button或者input标签添加属性data-ajax
*   对按钮有效
**/
$('document').ready(function () {

    var index = 0;
    var els = $.merge($('button[data-ajax]'), $('input[data-ajax]'));

    els.each(function () {
        var $this = $(this);
        index = index + 1;
        $this.attr('data-ajax-index', index);
        $this.click(function () {
            ajax_quenen.push($this, $this.attr('data-ajax-index'));
        });
    });

    $.ajaxSetup({
        beforeSend: function (xhr, setting) {
            var $el = $(event.srcElement);
            ajax_quenen.push($el, $el.attr('data-ajax-index'));

            var matched = ajax_quenen.get_wait_for_request();
            if (matched) {
                var $el = matched.$el;
                $el.text('loading....');
                $el.prop('disabled', true);
                xhr.ajax_index = matched.index;
                matched.is_requesting = true;
            }
        },
        complete: function (xhr, ts) {
            var matched = ajax_quenen.find(xhr.ajax_index);
            if (matched) {
                var $el = matched.$el;
                $el.text(matched.orginal_text);
                $el.prop('disabled', false);

                ajax_quenen.remove(matched.index);
            }
        }
    });

});